package com.zxh.blog.utils;

import com.zxh.blog.exception.BadRequestException;
import com.zxh.blog.redis.FastJsonRedisSerializer;
import com.zxh.blog.redis.service.RedisService;
import com.zxh.blog.vo.RedisVo;
import com.zxh.blog.web.security.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前登录的用户名
 *
 * @author zhangxh
 * @date 2019-01-17
 */
@Component
public class SecurityContextHolder {
    @Autowired
    private RedisService redisService;
    @Value("${jwt.header}")
    private  String tokenHeader;

    public  UserDetails getUserDetails(HttpServletRequest request) {
        UserDetails userDetails = null;

        try {
            final String requestHeader = request.getHeader(tokenHeader);

            String username = null;
            String authToken = null;
            if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
                authToken = requestHeader.substring(7);
            }
            FastJsonRedisSerializer<SysUser> fastJsonRedisSerializer=new FastJsonRedisSerializer<SysUser>(SysUser.class);
            byte[] values=redisService.getByteValue(authToken);
            userDetails =fastJsonRedisSerializer.deserialize(values);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期");
        }
        return userDetails;
    }
}
